<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="registerForm"
    :rules="registerRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
    @submit.prevent
  >
    <el-row style="margin-right: -10px; margin-left: -10px">
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>

      <!-- 第一步 输入学号获得打码手机号 -->
      <el-col v-if="step === 1" style="padding-right: 10px; padding-left: 10px">
        <el-form-item :label="t('sys.login.reg.step1')" prop="step1Username">
          <el-input
            v-model="registerForm.step1Username"
            :placeholder="t('common.inputTextPlaceholder') + t('sys.login.reg.step1Username')"
            :prefix-icon="iconAvatar"
            size="large"
            @keydown.enter="handleNextStep"
          />
        </el-form-item>
      </el-col>

      <!-- 第二步 确认手机可用性 点击确定发送验证码 -->
      <el-col v-if="step === 2" style="padding-right: 10px; padding-left: 10px">
        <div class="reg-text">
          {{ t('sys.login.reg.step2', { phone: registerForm.step1TempPhone }) }}
        </div>
      </el-col>

      <!-- 第三步 输入收到的验证码 -->
      <el-col v-if="step === 3" style="padding-right: 10px; padding-left: 10px">
        <el-form-item :label="t('sys.login.reg.step3')" prop="step3Code">
          <div class="w-full">
            <div class="flex justify-center gap-[10px] w-full">
              <el-input
                ref="codeInput1"
                v-model="registerForm.step3Code1"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(2)"
                @click="changeNext(1)"
              />
              <el-input
                ref="codeInput2"
                v-model="registerForm.step3Code2"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(3)"
                @click="changeNext(2)"
              />
              <el-input
                ref="codeInput3"
                v-model="registerForm.step3Code3"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(4)"
                @click="changeNext(3)"
              />
              <el-input
                ref="codeInput4"
                v-model="registerForm.step3Code4"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(5)"
                @click="changeNext(4)"
              />
              <el-input
                ref="codeInput5"
                v-model="registerForm.step3Code5"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(6)"
                @click="changeNext(5)"
              />
              <el-input
                ref="codeInput6"
                v-model="registerForm.step3Code6"
                style="width: 40px"
                :maxlength="1"
                @input="changeNext(7)"
                @click="changeNext(6)"
              />
            </div>
            <el-link
              style="float: right"
              type="primary"
              :underline="false"
              :disabled="cooldown > 0"
              @click="verify?.show()"
              >{{ t('sys.login.reg.step3Resend')
              }}<span v-if="cooldown > 0">({{ cooldown }})</span></el-link
            >
          </div>
        </el-form-item>
      </el-col>

      <!-- 第四步 验证码认证通过 显示完整信息并输入初始密码 -->
      <el-col v-if="step === 4" style="padding-right: 10px; padding-left: 10px">
        <el-descriptions :title="t('sys.login.reg.step4')" :column="1">
          <el-descriptions-item :label="t('sys.login.reg.step4Username')"
            >{{ registerForm.step4Username }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sys.login.reg.step4StudentName')"
            >{{ registerForm.step4StudentName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('login.mobileNumber')"
            >{{ registerForm.step4Phone }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sys.login.reg.step4ArpNumber')"
            >{{ registerForm.step4ArpNumber }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sys.login.reg.step4ResearchDept')"
            >{{ registerForm.step4ResearchDept }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="mt-[20px] mb-[10px]">{{ t('sys.login.reg.step4PasswordTitle') }}</div>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            auto-complete="off"
            :placeholder="t('common.inputTextPlaceholder') + t('sys.login.reg.step4Password')"
            size="large"
            :prefix-icon="iconLock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            size="large"
            auto-complete="off"
            :placeholder="t('common.inputTextPlaceholder') + t('sys.login.reg.step4Password2')"
            :prefix-icon="iconLock"
            show-password
          />
        </el-form-item>
      </el-col>

      <!-- 前4步的取消|确认按钮 -->
      <el-col v-if="step < 4" :span="12" style="padding-right: 10px; padding-left: 10px">
        <XButton
          :disabled="nextLoading"
          :title="t('sys.login.cancel')"
          class="w-[100%]"
          @click="handleBackLogin"
        />
      </el-col>
      <el-col v-if="step < 4" :span="12" style="padding-right: 10px; padding-left: 10px">
        <XButton
          :loading="nextLoading"
          :title="t('sys.login.next')"
          class="w-[100%]"
          type="primary"
          @click="handleNextStep"
        />
      </el-col>

      <!-- 第五步的注册按钮 -->
      <el-col v-if="step == 4" :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.register')"
            class="w-[100%]"
            type="primary"
            @click="handleRegister"
          />
        </el-form-item>
      </el-col>

      <!-- 短信captcha弹窗 -->
      <Teleport to="body">
        <Verify
          ref="verify"
          :captchaType="captchaType"
          :imgSize="{ width: '400px', height: '200px' }"
          mode="pop"
          @success="handleSendSms"
        />
      </Teleport>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useLoginState } from './useLogin'

defineOptions({ name: 'RegisterForm' })

const { t } = useI18n()
const iconHouse = useIcon({ icon: 'ep:house' }) as string
const iconAvatar = useIcon({ icon: 'ep:avatar' }) as string
const iconLock = useIcon({ icon: 'ep:lock' }) as string
const formLogin = ref()
const { handleBackLogin, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()

const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)

watch(
  () => getShow.value,
  (val) => {
    if (val) {
      step.value = 1
      // 重置
      registerForm.step1Username = ''
      registerForm.step1Type = 2
      registerForm.step1TempPhone = ''
      registerForm.accountId = ''
      registerForm.step3Code1 = ''
      registerForm.step3Code2 = ''
      registerForm.step3Code3 = ''
      registerForm.step3Code4 = ''
      registerForm.step3Code5 = ''
      registerForm.step3Code6 = ''
      registerForm.step3Code = ''
      registerForm.step3TempToken = ''
      registerForm.step4Username = ''
      registerForm.step4StudentName = ''
      registerForm.step4Phone = ''
      registerForm.step4ArpNumber = ''
      registerForm.step4ResearchDept = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
    }
  },
  {
    immediate: true
  }
)

const step = ref(1)

const cooldown = ref(0)
const cooldownTimer = ref()
const resetCooldown = () => {
  cooldown.value = 60
  if (cooldownTimer.value) {
    clearInterval(cooldownTimer.value)
  }
  cooldownTimer.value = setInterval(() => {
    cooldown.value--
    if (cooldown.value <= 0) {
      clearInterval(cooldownTimer.value)
      cooldown.value = 0
    }
  }, 1000)
}

const equalToPassword = (rule, value, callback) => {
  if (registerForm.password !== value) {
    callback(new Error(t('sys.login.reg.step4PasswordMismatch')))
  } else {
    callback()
  }
}

const registerRules = {
  step1Username: [{ required: true, trigger: 'blur', message: t('sys.login.reg.step1') }],
  step3Code: [
    { required: true, trigger: 'blur', message: t('sys.login.reg.step3') },
    { min: 6, max: 6, message: t('sys.login.reg.step3'), trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: t('common.inputTextPlaceholder') + t('sys.login.reg.step4Password')
    },
    { min: 5, max: 20, message: t('sys.login.reg.passwordLengthError'), trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: t('sys.login.reg.passwordLengthError2'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: t('sys.login.reg.step4PasswordTip') },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
}

const registerForm = reactive({
  step1Username: '', // 第一步输入的学号
  step1Type: 2, // 第一步的学生类型 固定是2了 只有联培生需要
  step1TempPhone: '', // 第一步返回的打码手机号
  accountId: '', // 第一步返回的账号ID

  step3Code1: '',
  step3Code2: '',
  step3Code3: '',
  step3Code4: '',
  step3Code5: '',
  step3Code6: '',
  step3Code: '', // 第三步输入的完整验证码

  step3TempToken: '', // 第三步验证通过返回的临时token

  step4Username: '',
  step4StudentName: '',
  step4Phone: '',
  step4ArpNumber: '',
  step4ResearchDept: '',

  password: '',
  confirmPassword: ''
})

const codeInput1 = ref()
const codeInput2 = ref()
const codeInput3 = ref()
const codeInput4 = ref()
const codeInput5 = ref()
const codeInput6 = ref()

watchEffect(() => {
  registerForm.step3Code = `${registerForm.step3Code1}${registerForm.step3Code2}${registerForm.step3Code3}${registerForm.step3Code4}${registerForm.step3Code5}${registerForm.step3Code6}`
})

const nextLoading = ref(false)

const handleNextStep = async () => {
  // 每一步都先校验输入
  const valid = await formLogin.value.validate()
  if (!valid) {
    return
  }
  nextLoading.value = true

  try {
    // 每一步的处理不同
    switch (step.value) {
      case 1: {
        const username = registerForm.step1Username
        const userType = registerForm.step1Type
        const activeAccount = await LoginApi.getAccountActiveInfo(username, userType)
        if (activeAccount) {
          // 学号正确，进入下一步
          registerForm.accountId = activeAccount.id
          registerForm.step1TempPhone = activeAccount.phone
          step.value++
        } else {
          return
        }
        break
      }
      case 2: {
        // 显示弹窗 拉杆完获取验证码
        verify.value.show()
        break
      }
      case 3: {
        // 验证验证码
        const verifyResult = await LoginApi.verifySms({
          accountId: registerForm.accountId,
          code: registerForm.step3Code
        })
        if (verifyResult) {
          registerForm.step3TempToken = verifyResult
          // 查询完整信息
          const infoFull = await LoginApi.getAccountInfo({
            accountId: registerForm.accountId,
            token: verifyResult
          })
          if (infoFull) {
            registerForm.step4Username = infoFull.username
            registerForm.step4StudentName = infoFull.studentName
            registerForm.step4Phone = infoFull.studentPhone
            registerForm.step4ArpNumber = infoFull.arpNumber
            registerForm.step4ResearchDept = infoFull.researchDept
          }
          step.value++
        }
        break
      }
    }
  } finally {
    nextLoading.value = false
  }
}

const handleSendSms = async (params: any) => {
  nextLoading.value = true
  try {
    const res = await LoginApi.sendSms({
      accountId: registerForm.accountId,
      captchaVerification: params.captchaVerification
    })
    if (res) {
      resetCooldown()
      if (step.value === 2) {
        step.value++
      }
      await nextTick()
      changeNext(1)
    }
  } finally {
    nextLoading.value = false
  }
}

const changeNext = async (index: number) => {
  if (index === 1) {
    // 选中所有内容
    codeInput1.value.focus()
    codeInput1.value.select()
  } else if (index === 2) {
    codeInput2.value.focus()
    codeInput2.value.select()
  } else if (index === 3) {
    codeInput3.value.focus()
    codeInput3.value.select()
  } else if (index === 4) {
    codeInput4.value.focus()
    codeInput4.value.select()
  } else if (index === 5) {
    codeInput5.value.focus()
    codeInput5.value.select()
  } else if (index === 6) {
    codeInput6.value.focus()
    codeInput6.value.select()
  } else if (index === 7) {
    await nextTick()
    await handleNextStep()
  }
}

// 提交注册
const handleRegister = async () => {
  loginLoading.value = true
  try {
    const res = await LoginApi.setPassword({
      accountId: registerForm.accountId,
      token: registerForm.step3TempToken,
      password: registerForm.password
    })
    if (!res) {
      return
    }

    authUtil.removeLoginForm()
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      await push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
  }
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.reg-text {
  font-size: 14px;
  margin-bottom: 22px;
}

.light {
  .reg-text {
    color: #606266;
  }
}

.dark {
  .reg-text {
    color: #ffffff;
  }
}
</style>
